<template>
    <div class="first_audit">
        <!--电销分配订单-->
        <div class="search">
            <el-form ref="form" :inline="false" :model="form" :rules="rules">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <!--选择电销员-->
                        <el-form-item prop="firstSalesmanId" :label="$t('salesManage.selectTelSalesStaff')">
                            <el-select v-model="form.firstSalesmanId" @change="changeSalesman" style="width: calc(100% - 90px)">
                                <el-option v-for="item in selectList" :label="item.username" :value="item.userId" :key="item.userId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <!--分配给-->
                        <el-form-item prop="roleType" :label="$t('authority.allotTo')">
                            <el-select v-model="form.newSalesmanId" style="width: calc(100% - 60px)">
                                <el-option value="" :label="$t('verify.plsChoose')"></el-option><!--请选择-->
                                <el-option v-for="item in filterAuditor" :label="item.userName" :value="item.userId" :key="item.userId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <!--营销类型-->
                        <el-form-item prop="marketingType" style="width: 100%">
                            <el-select v-model="form.marketingType" @change="handleMarketTypeChange" :multiple="true" :placeholder="$t('salesManage.marketingType')" style="width: 100%"><!--营销类型-->
                                <el-option v-for="item in keyMap.marketingType()" :key="item.value" :value="item.value" :label="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!--所属APP-->
                        <el-form-item prop="appName">
                            <select-app-list v-model="form.appName" :multiple="true" :placeholder="$t('common.ownedApp')" :clearable="false"></select-app-list><!--所属APP-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="5"> 
                        <!-- 批次号 -->
                        <el-form-item prop="batchCode" >
                            <el-select v-model="form.batchCode"  :placeholder="$t('salesManage.batchNumber')" clearable  multiple collapse-tags style="width: 100%;">
                                <el-option v-for="code in batchCodeList" :key="code" :value="code" :label="code"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item>
                            <el-button :disabled="!form.appName.length || !form.marketingType.length" type="primary" @click="search">{{$t('common.search')}}</el-button>
                            <el-button :disabled="selectedListHandling.length===0||!form.newSalesmanId" type="primary" @click="move">{{$t('authority.allot')}}</el-button>
                            <el-button type="primary" @click="updateActiveTab">{{$t('authority.back')}}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!--end form-->
        </div>

        <div class="data_list_panel">
            <!--处理中-->
            <handling :active-tab="activeTabCur" v-if="activeTabCur === 'handling'" @selectedChange="selectedChange" @updateFresh="refresh=false" :search-form="form" :refresh='refresh'></handling>
        </div>
    </div>
</template>

<script>
import Pagination from "@/components/pagination";
import mixin from "@/service/mixin";
import Handling from "./handling";
import { keyMap } from '@/config';
import SelectAppList from '@/components/select-app-list';

export default {
    name: "customerDistribution",
    components: {
        Pagination,
        Handling,
        SelectAppList,
    },
    mixins: [mixin],
    props: {
        activeTab: {
            type: String
        },
        searchForm: {
            type: Object
        }
    },
    data() {
        return {
            keyMap,
            refresh: true,
            batchCodeList:[],
            form: {
                firstSalesmanId: '',
                newSalesmanId: '',
                marketingType: [],
                appName: [],
                salesmanName: '',
                batchCode:[]
            },
            rules: {},
            selectList: [],
            selectedList: [],
            selectedListHandling:[],
            selectedListUnsigned:[],
            auditorList: [],
            activeTabCur: "handling",
            filterAuditor: [], // 分配给的人员
        };
    },
    watch: {
        activeTabCur(val) {
            if (val === "customerDistribution") {
                this.form.firstSalesmanId = this.searchForm.userId;
                this.form.newSalesmanId = "";
                this.page.currentPage = 1;
                // this.getTableData();
                this.getSelectOption();
            }
        },
    },
    computed: {
        // filterAuditor() {
        //     return this.selectList.filter(
        //         item => item.userId !== this.form.firstSalesmanId
        //     );
        // }
    },
    methods: {
        handleMarketTypeChange(val) {
            this.batchCodeList = [];
            this.form.batchCode = [];
            if (val) {
                console.warn(val.join(','))
                const params = {
                    marketingType: val.join(','), // 营销类型 1 还款未复借，2白名单
                    currentStatus: '1', // 当前状态 1 待处理 2 已处理
                };
                this.$api.telSales.getUserBatchCodeList(params).then(res => {
                    const { status, data } = res;
                    if ('1' === status) {
                        this.batchCodeList = data.data;
                    }
                });
            }
        },
        selectedChange(selectedList,type){
            switch (type) {
                case 'handling':
                    this.selectedListHandling=selectedList;
                    break;
                default:
                    break;
            }
        },
        changeSalesman() {
            this.page.currentPage = 1;
            const selectObj =  this.selectList.filter(item => item.userId === this.form.firstSalesmanId);
            this.form.salesmanName = selectObj[0]?selectObj[0].username:'';
            // 重新获取分配数据
            const { appName, marketingType } = this.form;
            if (appName.length && marketingType.length) {
                this.search();
            } else {
                this.form.newSalesmanId = '';
                this.filterAuditor = [];
            }
        },
        getSelectOption() {
            this.$api.telSales.getAllUserInfo({roleId: 1}).then(res => {
                const { status, data, error } = res;
                if ("1" === status && "00000000" === error && data.data) {
                    this.selectList = data.data;
                }
            });
        },
        move() {
            switch (this.activeTabCur) {
                case 'handling':
                    this.selectedList = this.selectedListHandling;
                    this.submitHandling();
                    break;
                default:
                    break;
            }
        },
        submitHandling(){
            if (this.selectedList.length === 0) {
                this.$message.warning(this.$tc("authority.chooseOrder"));
                return false;
            }
            const params = {
                "salesmanId": this.form.newSalesmanId,
                "telUserIdList":this.selectedList
            }
            this.$api.telSales.distributeUserList(params).then(res => {
                const { status, error } = res;
                if ("1" === status && "00000000" === error) {
                    this.$message.successOneSecond(this.$tc("common.successfulOperation"));
                    this.refresh=!this.refresh;
                    // this.getTableData();
                }
            });
        },
        updateActiveTab() {
            this.$emit("updateActiveTab", "customAssistant");
        },
        geDetail(row) {
            this.$openNewBlank(
                `#/conf/audit-detail/${row.userId}/${this.$root.local}/${row.orderNid}`
            );
        },
        search() {
            this.refresh = true;
            const { appName, marketingType, firstSalesmanId, newSalesmanId } = this.form;
            const params = {
                appName: appName.join(','),
                marketingType: marketingType.join(','),
            };
            this.$api.telSales.listCanDistribution(params).then(res => {
                const { status, data, error } = res;
                if ("1" === status && "00000000" === error && data) {
                    // this.filterAuditor = data.filter(item => item.userId !== firstSalesmanId);
                    this.filterAuditor = [];
                    this.form.newSalesmanId = '';
                    data.forEach(item => {
                        if (item.userId !== firstSalesmanId) {
                            this.filterAuditor.push(item);
                        }
                        if (newSalesmanId && newSalesmanId === item.userId && newSalesmanId !== firstSalesmanId) {
                            this.form.newSalesmanId = newSalesmanId;
                        }
                    });
                }
            });
        },
    },
    created() {
        if (this.activeTab === "customerDistribution") {
            this.form.firstSalesmanId = this.searchForm.userId;
            this.page.currentPage = 1;
            this.form.salesmanName = this.searchForm.username;
            // this.getTableData();
            this.getSelectOption();
        }
        if (this.form.firstSalesmanId === this.form.newSalesmanId) {
            this.form.newSalesmanId = "";
        }
    }
};
</script>

<style lang="scss" scoped>
.search {
    background-color: #fff;
    padding: 22px 40px 0;
}
.data_list {
    margin: 16px 24px;
    padding: 16px;
    background-color: #fff;
}
</style>
